﻿CREATE PROCEDURE [dbo].[CashRegistersDelete]
(
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
 
SET NOCOUNT ON

IF (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intRet = Id
FROM [CD].[CashRegisters] WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF EXISTS (
SELECT TOP (1) Id
FROM [CD].[CashRegisterShifts] WHERE CashRegisterId = @Original_Id )
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Для этой кассы существуют смены!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

	SET NOCOUNT OFF;
DELETE FROM [CD].[CashRegisters] WHERE Id = @Original_Id

RETURN 0